package com.vm.activity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.UUID;

import com.android.volley.RequestQueue;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.vm.commons.CurrentUser;
import com.vm.commons.StringUtil;
import com.vm.commons.VMConst;
import com.vm.db.LocalUserInfoDao;
import com.vm.utils.MyDisplayImageOptions;
import com.vm.utils.MyVolley;
import com.vm.utils.UploadUtil;
import com.vm.widget.CircularImage;
import com.wwtscapp.apk.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @ProjectName: [WeiMai]
 * @Author: [kent.wang]
 * @CreateDate: [2015年2月3日 上午9:52:32]
 * @Version: [v1.0]
 * 
 */
public class PersonCenterActivity extends Activity {

	private LocalUserInfoDao luidao;
	TextView tv_account;
	CircularImage iv_photo_camera;
	RequestQueue requestQueue;
	TextView tv_intergral;
	Button btn_exit;

	RelativeLayout rlayout_order;
	RelativeLayout rlayout_address;

	private Uri photoUri;

	private final int PIC_FROM_CAMERA = 1;
	private final int PIC_FROM＿LOCALPHOTO = 0;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.slideing_menu);

		// init();
		luidao = new LocalUserInfoDao(this);
		requestQueue = MyVolley.getRequestQueue();

		if (CurrentUser.USERID != null) {
			tv_account.setText(CurrentUser.USERNAME);
			if (CurrentUser.IMAGEURL != null) {

				ImageLoader.getInstance().displayImage(
						VMConst.URL + CurrentUser.IMAGEURL, iv_photo_camera,
						MyDisplayImageOptions.getInstance());
			}

			tv_intergral.setText(Integer.toString(CurrentUser.INTERGRAL));

		} else {
			Toast toast = Toast.makeText(PersonCenterActivity.this, "没有用户数据",
					Toast.LENGTH_SHORT);
			toast.show();
		}

	}

	/**
	 * 初始化
	 */
	// public void init() {
	// // LinearLayout llayout_back = (LinearLayout)
	// findViewById(R.id.llayout_back);
	// // llayout_back.setOnClickListener(btn_backListener);
	//
	// // tv_account = (TextView) findViewById(R.id.tv_account);
	//
	// iv_photo_camera = (CircularImage) findViewById(R.id.iv_photo_camera);
	// tv_intergral = (TextView) findViewById(R.id.tv_intergral);
	//
	// btn_exit = (Button) findViewById(R.id.btn_exit);
	// btn_exit.setOnClickListener(btn_exitClickListener);
	//
	// // rlayout_order = (LinearLayout) findViewById(R.id.layout_order);
	// rlayout_order.setOnClickListener(order_ClickListener);
	// rlayout_address = (RelativeLayout) findViewById(R.id.rlayout_address);
	// rlayout_address.setOnClickListener(address_ClickListener);
	// iv_photo_camera.setOnClickListener(photo_Listener);
	// }

	OnClickListener address_ClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(PersonCenterActivity.this,
					AddressManageActivity.class);
			startActivity(intent);
		}
	};

	OnClickListener order_ClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(PersonCenterActivity.this,
					OrderActivity.class);
			startActivity(intent);
		}
	};

	OnClickListener btn_exitClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			luidao.delete();
			CurrentUser.clear();
			PersonCenterActivity.this.finish();
		}
	};

	OnClickListener photo_Listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			final CharSequence[] items = { "相机拍照", "本地图片" };
			AlertDialog.Builder builder = new AlertDialog.Builder(
					PersonCenterActivity.this);
			builder.setCancelable(true);
			builder.setItems(items, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					if (which == 0) {
						doHandlerPhoto(PIC_FROM_CAMERA);// 用户点击了从照相机获取
					}
					if (which == 1) {
						doHandlerPhoto(PIC_FROM＿LOCALPHOTO);// 从相册中去获取
					}
				}

			});
			AlertDialog alert = builder.create();
			alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
			alert.show();
		}

	};

	/**
	 * 根据不同方式选择图片设置ImageView
	 * 
	 * @param type
	 *            0-本地相册选择，非0为拍照
	 */
	private void doHandlerPhoto(int type) {
		try {
			// 保存裁剪后的图片文件
			File pictureFileDir = new File(
					Environment.getExternalStorageDirectory(), "/upload");
			if (!pictureFileDir.exists()) {
				pictureFileDir.mkdirs();
			}
			File picFile = new File(pictureFileDir, "upload.jpeg");
			if (!picFile.exists()) {
				picFile.createNewFile();
			}
			photoUri = Uri.fromFile(picFile);

			if (type == PIC_FROM＿LOCALPHOTO) {
				Intent intent = getCropImageIntent();
				startActivityForResult(intent, PIC_FROM＿LOCALPHOTO);
			} else {
				Intent cameraIntent = new Intent(
						MediaStore.ACTION_IMAGE_CAPTURE);
				cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
				startActivityForResult(cameraIntent, PIC_FROM_CAMERA);
			}

		} catch (Exception e) {
			Log.i("HandlerPicError", "处理图片出现错误");
		}
	}

	/**
	 * 调用图片剪辑程序
	 */
	public Intent getCropImageIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		setIntentParams(intent);
		return intent;
	}

	/**
	 * 启动裁剪
	 */
	private void cropImageUriByTakePhoto() {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(photoUri, "image/*");
		setIntentParams(intent);
		startActivityForResult(intent, PIC_FROM＿LOCALPHOTO);
	}

	/**
	 * 设置公用参数
	 */
	private void setIntentParams(Intent intent) {
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 600);
		intent.putExtra("outputY", 600);
		intent.putExtra("noFaceDetection", true); // no face detection
		intent.putExtra("scale", true);
		intent.putExtra("return-data", false);
		intent.putExtra("scaleUpIfNeeded", true);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case PIC_FROM_CAMERA: // 拍照
			try {
				cropImageUriByTakePhoto();
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case PIC_FROM＿LOCALPHOTO:
			try {
				if (photoUri != null) {
					Bitmap bitmap = decodeUriAsBitmap(photoUri);
					String path = StringUtil.getFilePath();
					File dirFile = new File(path);
					if (!dirFile.exists()) {
						dirFile.mkdir();
					}
					File myCaptureFile = new File(path + "test");
					BufferedOutputStream bos = new BufferedOutputStream(
							new FileOutputStream(myCaptureFile));
					bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
					bos.flush();
					bos.close();
					String fileName = UUID.randomUUID().toString();
					UploadUtil.uploadFile(myCaptureFile, fileName);
					// CurrentUser.IMAGEURL = StringUtil

					iv_photo_camera.setImageBitmap(bitmap);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		}
	}

	private Bitmap decodeUriAsBitmap(Uri uri) {
		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeStream(getContentResolver()
					.openInputStream(uri));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
		return bitmap;
	}

	/**
	 * imgbtn_search_back 返回按钮监听
	 */
	OnClickListener btn_backListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			onBackPressed();
		}
	};

	/**
	 * 手机自带返回按钮监听
	 */
	@Override
	public void onBackPressed() {
		super.onBackPressed();

	}

}
